from datetime import date, datetime, timedelta

import math
from sqlalchemy import func
from sqlalchemy.orm import Query


class QueryTools:
    @staticmethod
    def get_page_sum(query_object, primary_key, page_size=20):
        """
        优化获取页面的查询方法
        :param query_object:需要在limit之前的对象
        :param primary_key: 用来计数的字段
        :param page_size: 每页的数量
        :return:
        """
        count = query_object.with_entities(func.count(primary_key)).scalar() or 0
        return math.ceil(count / page_size)

    # 打印sqlalchemy的sql语句 直接把不带.all和.first的语句作为第一个参数传入即可
    @staticmethod
    def render_query(statement, dialect=None):

        if isinstance(statement, Query):
            if dialect is None:
                dialect = statement.session.bind.dialect
            statement = statement.statement
        elif dialect is None:
            dialect = statement.bind.dialect

        class LiteralCompiler(dialect.statement_compiler):

            def visit_bindparam(self, bindparam, within_columns_clause=False,
                                literal_binds=False, **kwargs):
                return self.render_literal_value(bindparam.value, bindparam.type)

            def render_array_value(self, val, item_type):
                if isinstance(val, list):
                    return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
                return self.render_literal_value(val, item_type)

            def render_literal_value(self, value, type_):
                if isinstance(value, int):
                    return str(value)
                elif isinstance(value, (str, date, datetime, timedelta)):
                    return "'%s'" % str(value).replace("'", "''")
                elif isinstance(value, list):
                    return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
                return super(LiteralCompiler, self).render_literal_value(value, type_)

        query_msg = LiteralCompiler(dialect, statement).process(statement)
        return query_msg